#include "mainscene.h"
#include"config.h"
#include "map.h"
#include<QIcon>
#include<QPainter>
#include<QMouseEvent>

MainScene::MainScene(QWidget *parent)
    : QWidget(parent)
{
    //调用初始化场景
    initScene();
    //启动游戏
    playGame();
}

MainScene::~MainScene()
{
}

void MainScene::initScene()
{
    //设置窗口固定
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);
    //设置标题
    setWindowTitle(GAME_TITLE);
    //设置图标
    setWindowIcon(QIcon(":/resource/title"));
    //定时器
    m_Timer.setInterval(GAME_RATE);
}

void MainScene::playGame()
{
    //启动定时器
    m_Timer.start();

    //监听定时器信号
    connect(&m_Timer,&QTimer::timeout,[=](){
        //更新游戏中元素坐标
        updatePosition();

        //绘制到屏幕中
        update();
    });
}

void MainScene::updatePosition()
{
    //更新地图坐标
    m_map.mapPosition();

    //测试子弹
    //temp_Bullet.m_Free=false;
    //temp_Bullet.updatePosition();
}

void MainScene::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    //绘制地图
    painter.drawPixmap(0,m_map.m_map1_posY,m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY,m_map.m_map2);

    //绘制豌豆
    painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Plane);

    //测试子弹
    //painter.drawPixmap(temp_Bullet.m_X,temp_Bullet.m_Y,temp_Bullet.m_Bullet);

}

void MainScene::mouseMoveEvent(QMouseEvent *event)
{
    int x=event->x()-m_hero.m_Rect.width()*0.5;
    int y=event->y()-m_hero.m_Rect.height()*0.5;

    //边界检测
    if(x<=0)
        x=0;
    if(x>=GAME_WIDTH-m_hero.m_Rect.width())
        x=GAME_WIDTH-m_hero.m_Rect.width();
    if(y<=0)
        y=0;
    if(y>=GAME_HEIGHT-m_hero.m_Rect.height())
        y=GAME_HEIGHT-m_hero.m_Rect.height();

    m_hero.setposition(x,y);
}

